package com.framework.workflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.framework.workflow.constant.DataDict;
import com.framework.workflow.mapper.WfButtonMapper;
import com.framework.workflow.model.WfButton;
import com.framework.workflow.params.WfButtonParam;
import com.framework.workflow.service.IWfButtonService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

import static com.framework.workflow.em.ButtonEnum.parseName;


/**
 * 按钮配置
 * @author zzg
 */
@Service
public class WfButtonService implements IWfButtonService {
    @Autowired
    private WfButtonMapper baseMapper;

    @Override
    public List<WfButton> list(WfButtonParam param) {
        return baseMapper.listButton(param);
    }

    @Override
    public String save(WfButton param) {
        if (StringUtils.isEmpty(param.getId())) {
            baseMapper.insert(param);
        } else {
            baseMapper.updateById(param);
        }

        return param.getId();
    }

    @Override
    public void addSimple(WfButton param) {
        //删除该模块和该节点的数据
        LambdaQueryWrapper<WfButton> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WfButton::getTaskDefKey, param.getTaskDefKey());
        queryWrapper.eq(WfButton::getProcDefKey, param.getProcDefKey());
        baseMapper.delete(queryWrapper);

        //循环插入
        for (String buttonName: param.getName().split(DataDict.Separator.COMMA.toString())){
            if (StringUtils.isBlank(buttonName)) {
                continue;
            }
            param.setName(buttonName);
            WfButton data = new WfButton();
            data.setCode(Objects.requireNonNull(parseName(buttonName)).getValue());
            data.setName(buttonName);
            data.setProcDefKey(param.getProcDefKey());
            data.setTaskDefKey(param.getTaskDefKey());

            baseMapper.insert(data);
        }
    }

   @Override
    public void delete(List<String> ids) {
       ids.forEach(id -> baseMapper.deleteById(id));
    }

    @Override
    public void delByKey(String key) {
        baseMapper.deleteByKey(key);
    }

    @Override
    public List<WfButton> listCurrNodeBtn(WfButtonParam param) {
        return baseMapper.list(param);
    }

    @Override
    public void update(WfButton param) {
       WfButton entity = baseMapper.selectById(param.getId());
       BeanUtils.copyProperties(param, entity, "id");
       baseMapper.updateById(entity);
    }

   @Override
    public WfButton findOne(String id) {
       return baseMapper.selectById(id);
    }
}
